<?php
/**
 * Created by PhpStorm.
 * User: HarrisHuang
 * Date: 17/5/9
 * Time: 00:33
 */
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Admin;
use Illuminate\Support\Facades\Redis;

class AdminController extends Controller
{

    public function index()
    {
        return view('index');
    }

    /**
     * 添加管理员
     * @return mixed
     */
    public function add(Request $request)
    {
        $name = trim($request->input('name'));
        $pwd = trim($request->input('password'));
        $rePwd = trim($request->input('rePassword'));
        if ($name == '' || $pwd == '') {
            return $this->error('参数异常');
        }
        if ($pwd != $rePwd) {
            return $this->error('密码输入不一致');
        }

        //用户名是否存在
        $res = Admin::where('name', $name)->first();
        if ($res) {
            return $this->error('用户名已存在~');
        }

        $data = [
            'name' => $name,
            'password' => password_hash($pwd, PASSWORD_BCRYPT),
            'status' => 1,
            'addTime' => time(),
        ];
        Admin::create($data);
        return $this->success();

    }

    /**
     * 登陆接口
     *
     */
    public function login(Request $request)
    {
        $name = trim($request->get('name'));
        $pwd = trim($request->input('password'));
        $res = Admin::where('name', $name)->first();
        if (!$res) {
            return $this->error('用户名不存在');
        }
        if (password_verify($pwd, $res['password'])) {
            //@todo redis 存储token
            $token = md5(time() . 'harris');
            Redis::set($token, json_encode($res));
            Redis::expire($token, 3600);
            return $this->success(['token' => $token]);
        } else {
            return $this->error('密码错误');
        }
    }

    public function lists(Request $request)
    {
        $pageSize = $request->get('pageSize', 10);
        $list = Admin::where('status', 1)->paginate($pageSize);
        $list = $list->toArray();
        $res = [
            'total' => $list['total'],
            'data' => $list['data'],
        ];
        return $this->success($res);
    }


}